package org.dbstar.scheduler.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;

/**
 * 时间处理相关工具类
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-18
 */
public class CalendarUtils {
	public static Calendar date(String val, String pattern) throws java.text.ParseException {
		Date date = new SimpleDateFormat(pattern).parse(val);
		if (date != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			return calendar;
		} else {
			return null;
		}
	}

	public static String format(Calendar calendar, String pattern) {
		return calendar == null ? null : DateFormatUtils.format(calendar, pattern);
	}

	public static String convert(String val, String srcPattern, String destPattern) throws java.text.ParseException {
		return format(date(val, srcPattern), destPattern);
	}

	public static int dayOfWeek(Calendar calendar) {
		return field(calendar, Calendar.DAY_OF_WEEK);
	}

	public static int dayOfYear(Calendar calendar) {
		return field(calendar, Calendar.DAY_OF_YEAR);
	}

	public static int field(Calendar calendar, int field) {
		return calendar == null ? 0 : calendar.get(field);
	}

	public static Calendar roll(Calendar calendar, int field, int amount) {
		if (calendar == null) {
			return null;
		} else {
			Calendar c2 = Calendar.getInstance();
			c2.setTimeInMillis(calendar.getTimeInMillis());
			c2.add(field, amount);
			return c2;
		}
	}
}
